<?php

namespace app\admin\model\user;

use app\common\model\User;
use think\Config;
use think\Db;
use think\Model;


class Withdraw extends Model
{





    // 表名
    protected $table = 'withdraw_log';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    protected $dateFormat='Y-m-d H:i:s';

    // 追加属性
    protected $append = [

    ];


    protected static function init()
    {
        parent::init();

        self::afterUpdate(function ($row) {
            $changed = $row->data;
            if ($changed['status']==2) {
                $user=User::get($changed['uid']);
                $user->money +=$changed['money'];
                $user->save();
            }
        });
    }

    /**
     * 提现
     * @param $user
     * @param $money
     * @return Withdraw
     */
    public function run($user,$money,$type){

        $charge_rate=Config::get('site.withdraw_charge') / 100;

        if($type==1) {
            $data = [
                'uid' => $user->id,
                'money' => $money,
                'before' => $user->money,
                'after' => $user->money - $money,
                'charge' => bcmul($money, $charge_rate, 2),
                'memo' => '余额提现'
            ];
            $user->money -= $money;
            $user->save();
        }elseif ($type ==2){
            $data = [
                'uid' => $user->id,
                'money' => $money,
                'before' => $user->earnings,
                'after' => $user->earnings - $money,
                'charge' => bcmul($money, $charge_rate, 2),
                'memo' => '推广收益提现'
            ];
            $user->earnings -= $money;
            $user->save();
            $insert=$data;
            unset($insert['charge']);
            $insert['createtime']=time();
            Db::name('user_earnings_log')->insert($insert);
        }

        $data['type'] = $type;
        return self::create($data);
    }









    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'uid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
